<?php


namespace App\Services;

use App\Services\GameMoneyReissue;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class GameRechargeService extends BasePayService
{
    private $uid;
    private $money;
    private $pay_type;
    private $game_info;
    private $orderNo;

    /**
     * 支付
     * @param int $uid
     * @param int $money
     * @param $pay_type
     * @return mixed
     */
    public static function startPay(int $uid,int $money, $pay_type, $game_info, $orderNo, $platName)
    {
        if ($money < 10) {
            throw new \Exception('充值金额最低为10元');
        }
        return (new self($uid, $money, $pay_type, $game_info, $orderNo, $platName))->pay();
    }

    /**
     * 回调
     * @param array $notifyInfo
     * @throws \Exception
     */
    public static function notify(array $notifyInfo)
    {
        $orderInfo = DB::table('game_recharge_order')->where('order_no', $notifyInfo['ordernumber'])
            ->where('pay_status', 2)
            ->first();
        if (!$orderInfo) {
            throw new \Exception('未查询到待支付订单');
        }
        $that = new self($orderInfo->user_id, $orderInfo->money, $orderInfo->pay_type);
        $that->orderInfo = $orderInfo;

        $userInfo = DB::table('users')->find($that->orderInfo->user_id);
        if (!$userInfo) {
            throw new \Exception('用户信息错误');
        }
        // 更新订单信息
        $update = [
            'resp_params' => json_encode($notifyInfo),
            'pay_status' => $notifyInfo['status'] == 1 ? 1 : 3,
            'plat_order_no' => $notifyInfo['tradeno']
        ];

        Db::beginTransaction();
        try {
            if (!DB::table('game_recharge_order')->where('id', $orderInfo->id)->update($update)) {
                throw new \Exception('更新订单失败');
            }
            //实时发送到游戏
            GameMoneyReissue::gameMoneyReissue($notifyInfo['ordernumber']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * RechargeService constructor.
     * @param int $uid
     * @param int $money
     * @param string $pay_type
     * @throws \Exception
     */
    public function __construct(int $uid = 0,int $money = 0,string $pay_type = 'WEIXIN', $game_info = [], $orderNo = '', $platName = '')
    {
        parent::__construct($platName);
        $this->uid = $uid;
        $this->money = $money;
        $this->pay_type = $pay_type;
        $this->game_info = $game_info;
        $this->orderNo = $orderNo;
    }

    /**
     * 发起支付
     * @return array
     * @throws AppRuntimeException
     */
    private function pay()
    {
        // 计算抵扣金额
        $data = [
            'gameuser'=> $this->game_info['game_account'] ?? 'wanfu591',
            'paytype'=>$this->pay_type,
            'money'=>$this->money,
            'ordernumber'=>$this->getOrderNo($this->uid, 3),
            'remark' => 3,
        ];
        $this->createOrder($data);
        $payInfo = $this->request('', $data);
        if ($payInfo['resultcode'] != 200) {
            throw new \Exception($payInfo['resultmsg']);
        }
        // 如果type为1，则处理成2
        if ($payInfo['resultdata']['type'] == 1) {
            // 将内容写入缓存
            Cache::put(self::getPayPageCacheKey($this->orderId, 1), $payInfo['resultdata']['data'], 3600);
            $payInfo['resultdata']['type'] = 2;
            $payInfo['resultdata']['data'] = '/api/pay/payPage/1/'.$this->orderId;
        }
        return ['order_id' => $this->orderId, 'pay_info' => $payInfo];
    }


    /**
     * 创建订单
     * @param $req
     * @throws AppRuntimeException
     */
    private function createOrder($req)
    {
        $userInfo = DB::table('users')->find($this->uid);
        $order = [
            'pay_plat_id' => $this->payPlat->id,
            'user_id' => $this->uid,
            'unionid' => $userInfo->unionid,
            'money' => $this->money,
            'req_params' => json_encode($req),
            'pay_type' => $this->pay_type,
            'order_no' => $req['ordernumber'],
            'plat_order_no' => '',
            'contact' => $this->game_info['qq'] ?? '',
            'pay_status' => 2,
            'game_account' => $this->game_info['game_account'] ?? '',
            'game_version' => $this->game_info['game_version'] ?? '',
            'game_server' => $this->game_info['game_server'] ?? '',
            'game_role' => $this->game_info['game_role'] ?? '',
            'create_time' => time(),
            'update_time' => time(),
            'site_host' => $_SERVER['HTTP_HOST'] ?? '',
            'order_type' => 1,
        ];
        $this->orderId = DB::table('game_recharge_order')->insertGetId($order);
        if (!$this->orderId) {
            throw new \Exception('生成订单失败');
        }
    }
}
